package dml

import (
	"fmt"
	"go-admin-auth/app/dal"
	"go-admin-auth/app/lib/lru"
	"go-admin-auth/app/models"
)

const (
	userLruKey = "user."
)

type userDML struct{}

var (
	UserDML         = &userDML{}
	userLruCache, _ = lru.New(200)
)

func (this *userDML) Get(id int) (*models.TUser, error) {
	lruKey := this.LruGetKey(id)
	val, isOk := userLruCache.Get(lruKey)
	if isOk {
		return val.(*models.TUser), nil
	}

	res, err := dal.UserDAO.Get(id)
	if err != nil {
		return res, err
	}
	userLruCache.Set(lruKey, res, 0)
	return res, err
}

func (this *userDML) Update(m *models.TUser) error {
	lruKey := this.LruGetKey(m.Id)
	this.LruPublishRemove(lruKey)
	return dal.UserDAO.Update(m)
}

func (this *userDML) Delete(id int) error {
	lruKey := this.LruGetKey(id)
	this.LruPublishRemove(lruKey)
	return dal.UserDAO.Delete(id)
}

func (this *userDML) RealDelete(id int) error {
	lruKey := this.LruGetKey(id)
	this.LruPublishRemove(lruKey)
	return dal.UserDAO.RealDelete(id)
}

/* ----  lru  ---- */

func (this *userDML) LruGetKey(key interface{}) string {
	return fmt.Sprintf("%s%v", userLruKey, key)
}

func (this *userDML) LruRemove(key string) bool {
	return userLruCache.Remove(key)
}

// 非单台机器提供服务的情况下， 完善此处
func (this *userDML) LruPublishRemove(key string) error {
	this.LruRemove(key)
	// TODO
	return nil
}

/* ----  lru  ---- */
